/**
 * Huisou.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */

package com.huisou.web.search;

import com.huisou.solrj.SolrServerUtil;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @description 以http方式控制索引 company：1288329 1288129 sale:2267534 2257534 news:80271 79000
 * @author chenzehe
 * @email hljuczh@163.com
 * @create 2012-6-29 下午03:12:18
 */
@Controller
public class IndexAction {
	// @ResponseBody
	// @RequestMapping(value = "/adddoc/index.htm", method = RequestMethod.GET)
	public String addDoc(HttpServletRequest request) throws Exception {
		String solrcore = "company";
		SolrServer server = SolrServerUtil.getSolrServer(solrcore);
		SolrInputDocument doc = new SolrInputDocument();
		
		doc.addField("id", "6025720");
		doc.addField("name", "北京友联亚泰机械制造有限责任公司");
		doc.addField("title", "北京友联亚泰机械制造有限责任公司");
		doc.addField("domain", "bjylyt");
		doc.addField("avatar", "http://img.e.huisou.com/upload/2012/07/07/6025720_middle_logo.jpg");
		doc.addField("summary", "北京友联亚泰机械制造有限公司，是科集、工、贸为一体的综合性实业性公司，主要研制制冷设备、烧烤设备、食品机械！如冰淇淋机、冷热饮机、刨冰机、炒冰机、炒货机、粉丝机、烤鸭炉、烤鸡炉、无烟烧烤机、豆腐豆浆机、玉米爆花机等产品。本公司立足于北京，面向全国世界致力于品牌建设和企业可持续发展、我们竭诚欢迎全国各地客商光临指导，洽谈业务。建立友好合作关系，共同创美好明天。");
		doc.addField("address", "北京市大兴区");
		doc.addField("etypeId", "114");
		doc.addField("etype", "有限责任公司");
		doc.addField("cateCode", "017079");
		doc.addField("professionId", "456");
		doc.addField("profession", "制冷设备");
		doc.addField("opmodeId", "7");
		doc.addField("opmode", "生产加工");
		doc.addField("business", "冰淇淋机 冷热饮机 刨冰机 炒冰机 烤禽箱 粉丝机 玉米爆花机 土耳其烤肉机 豆腐豆浆机");
		doc.addField("countryId", "1");
		doc.addField("country", "中国");
		doc.addField("stateId", "2");
		doc.addField("state", "北京市");
		doc.addField("cityId", "3");
		doc.addField("city", "北京市");
		doc.addField("status", "1");
		doc.addField("pid", "13");
		doc.addField("pCode", "017");
		doc.addField("pname", "机械及行业设备");
		doc.addField("grade", "2");
		doc.addField("totalPoint", "1116");
		doc.addField("fineFlg", "1");
		
		server.add(doc);
		server.commit();
		return "ok:" + new Date();
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete/bykeyword.htm")
	public String deleteByKeyWord(HttpServletRequest request) throws Exception {
		String solrcore = request.getParameter("solrcore");
		String keyword = request.getParameter("keyword");
		if (StringUtils.isNotBlank(solrcore) && StringUtils.isNotBlank(keyword)) {
			SolrServer server = SolrServerUtil.getSolrServer(solrcore);
			System.out.println(solrcore + " ; " + keyword);
			server.deleteByQuery("title:" + keyword);
			server.commit();
		}
		return "ok:" + new Date();
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete/byid.htm")
	public String deleteById(HttpServletRequest request) throws Exception {
		String solrcore = request.getParameter("solrcore");
		String id = request.getParameter("id");
		if (StringUtils.isNotBlank(solrcore) && StringUtils.isNotBlank(id)) {
			SolrServer server = SolrServerUtil.getSolrServer(solrcore);
			server.deleteById(id);
			server.commit();
		}
		return "ok:" + new Date();
	}
	
	// 索引
	@ResponseBody
	@RequestMapping(value = "/indeximport/index.htm", method = RequestMethod.GET)
	public String indexImport(HttpServletRequest request) throws Exception {
		if (!"huisou".equals(request.getParameter("password"))) {
			return "error";
		}
		Integer offset = Integer.parseInt(request.getParameter("offset"));
		Integer rows = Integer.parseInt(request.getParameter("rows"));
		Integer total = Integer.parseInt(request.getParameter("total"));
		String solrcore = request.getParameter("solrcore");
		String entity = request.getParameter("entity");
		String clear = request.getParameter("clear");
		startIndex(solrcore, entity, offset, rows, total, clear);
		return "ok:" + new Date();
	}
	
	// 清空索引
	@ResponseBody
	@RequestMapping(value = "/indexclear/index.htm", method = RequestMethod.GET)
	public String indexClear(HttpServletRequest request) throws Exception {
		if (!"huisou".equals(request.getParameter("password"))) {
			return "error";
		}
		Integer offset = 0;
		Integer rows = 0;
		Integer total = 1;
		String solrcore = request.getParameter("solrcore");
		String entity = request.getParameter("entity");
		String clear = "true";
		startIndex(solrcore, entity, offset, rows, total, clear);
		return "ok:" + new Date();
	}
	
	private void startIndex(String solrcore, String entity, Integer offset, Integer rows, Integer total, String clear) {
		if (StringUtils.isBlank(solrcore)) {
			solrcore = "company";
		}
		// 带有SolrCore的基地址
		String baseURL = "http://localhost:8084/" + solrcore;
		// 从哪一条开始
		if (offset < 0) {
			offset = 0;
		}
		// 每次索引多少条
		if (rows < 0) {
			rows = 5000;
		}
		// 总共有多少条
		// company 1293085
		if (total < 0) {
			total = 5000;
		}
		
		long start = System.currentTimeMillis();
		while (offset < total) {
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 600000);
				String suffix = buildURL(entity, offset, rows, clear);
				String url = baseURL + suffix;
				System.out.println("===================" + url + "======================");
				HttpGet method = new HttpGet(url);
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String retStr = httpClient.execute(method, responseHandler);
				System.out.println(retStr);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			if (rows < 1) {
				rows = 1;
			}
			offset += rows;
			
		}
		long end = System.currentTimeMillis();
		System.out.println("=========================" + (end - start) / 1000 + "=====================");
		
	}
	
	private String buildURL(String entity, Integer offset, Integer rows, String clear) {
		if (StringUtils.isBlank(clear)) {
			clear = "false";
		}
		StringBuilder url = new StringBuilder();
		url.append("/dataimport?command=full-import&clean=" + clear + "&commit=true&synchronous=true").append("&offset=" + offset).append("&rows=" + rows);
		if (StringUtils.isNotBlank(entity)) {
			url.append("&entity=" + entity);
		}
		return url.toString();
	}
}
